<?php
//领券人服务

namespace App\Services;

use App\Repositories\ReceiversRepository;
use Carbon\Carbon;

class ReceiverService
{

    /**
     * 获取列表
     * @param $query
     * @param $offset
     * @param $limit
     * @param $orderType
     * @return array|mixed
     */
    public static function getList($query = [], $offset = 0, $limit = 20, $orderType = 0)
    {
        //获取证书关联信息
        $repo = new ReceiversRepository();
        $repo->buildQuery($query);
        $list = $repo
            ->getList($offset, $limit, $orderType)
            ->toarray();

        return self::getListFormat($list);
    }

    /**
     * 获取单条
     * @param $query
     * @return arra
     */
    public static function getRow($query = [])
    {
        //获取证书关联信息
        $repo = new ReceiversRepository();
        $repo->buildQuery($query);
        $row = $repo
            ->getRow();
        if (!$row) {
            return [];
        }
        $row = $row->toArray();
        $list = self::getListFormat([$row]);

        return reset($list);
    }

    /**
     * 获取总数
     * @param $query
     * @return arra
     */
    public static function getTotal($query = [])
    {
        //获取证书关联信息
        $repo = new ReceiversRepository();
        $repo->buildQuery($query);

        return $repo->getTotal();
    }

    /**
     * 获取页面结构列表
     * @param $query
     * @param $page
     * @param $pageSize
     * @param $orderType
     * @return int[]
     */
    public static function getPageList($query = [], $page = 1, $pageSize = 20, $orderType = 0)
    {
        $output = [
            'total'     => 0,
            'totalPage' => 0,
            'pageSize'  => (int) $pageSize,
            'list'      => [],
        ];
        //获取证书关联信息
        $repo = new ReceiversRepository();
        $repo->buildQuery($query);
        $total = $repo->getTotal();
        if (!$total) {
            return $output;
        }
        $offset = ($page - 1) * $pageSize;
        $output['total'] = $total;
        $output['totalPage'] = (int) ceil($total / $pageSize);
        $list = $repo
            ->getList($offset, $pageSize, $orderType)
            ->toarray();
        //格式化列表信息
        $output['list'] = self::getListFormat($list);

        return $output;
    }


    /**
     * 格式化列表信息
     * @param $list
     * @return array
     */
    public static function getListFormat($list)
    {
        if (!$list) {
            return [];
        }
        foreach ($list as &$val) {
        }
        unset($val);

        return $list;
    }

    /**
     * 更新领取状态
     * @param $id
     * @param $receiveStatus
     * @return array
     */
    public static function updateReceiveStatus($id, $receiveStatus, $receiveDate = '')
    {
        $data = ['receive_status' => $receiveStatus];
        if($receiveDate) {
            $data['receive_date'] = $receiveDate;
        }
        if ($receiveStatus == 2) {
            //领取时更新领取时间
            $data['receive_date'] = Carbon::now()->toDateTimeString();
        }
        $res = (new ReceiversRepository())->updateFields($id, $data);
        if (!$res) {
            return resultError('更新失败');
        }

        return resultSuccess([], '更新成功');
    }


    /**
     * 批量保存
     * @param $dataList
     * @return array
     */
    public static function batchSave($dataList = [])
    {
        $saveDataList = [];
        foreach ($dataList as $data) {
            $item = [
                'activity_id' => $data['activity_id'], //活动id
                'name'        => $data['name'] ?? '', //姓名
                'id_number'   => $data['id_number'] ?? '', //身份证号
                'mobile'      => $data['mobile'] ?? '', //手机号
                'real_id'     => $data['real_id'] ?? 0, //自然人标识
                'birthday'    => '', //生日
                'gender'      => 1, //性别：1.男；2.女；
            ];

            if ($item['id_number']) {
                //根据身份证号获取生日
                $item['birthday'] = substr($item['id_number'], 6, 4).'-'.substr($item['id_number'], 10,
                        2).'-'.substr($item['id_number'], 12, 2);
                //根据身份证号获取性别
                $gender = substr($item['id_number'], 16, 1);
                $item['gender'] = $gender % 2 ? 1 : 2;
            }

            $saveDataList[] = $item;
        }
        unset($dataList);

        $repo = new ReceiversRepository();
        $res = $repo->batchSave($saveDataList);

        if (!$res) {
            return resultError('保存失败');
        }

        return resultSuccess([], '保存成功');
    }


    /**
     * 获取领取人是否允许过期通知
     * @param $id
     * @param $status
     * @return array
     */
    public static function saveAllowExpireNotice($id, $status)
    {
        $data = [
            'allow_expire_notice' => $status,
        ];
        $res = (new ReceiversRepository())->updateFields($id, $data);
        if (!$res) {
            return resultError('更新失败');
        }

        return resultSuccess([], '更新成功');
    }


    /**
     * 更新券过期通知状态
     * @param $id
     * @param $receiveStatus
     * @return array
     */
    public static function updateExpireNotice($id, $status)
    {
        $data = [
            'expire_notice' => $status,
        ];
        $res = (new ReceiversRepository)->updateFields($id, $data);
        if (!$res) {
            return resultError('更新失败');
        }

        return resultSuccess([], '更新成功');
    }

    /**
     * 自增领取次数
     * @param $id
     * @return bool
     */
    public static function incrReceivedNum($id)
    {
        $incrNum = 1; //每次自增1
        $receiverInfo = self::getRow([
            'id' => $id,
        ]);
        if (!$receiverInfo) {
            return false;
        }
        $receivedNum = $receiverInfo['received_num'] + $incrNum;
        $receiveStatus = 2;
        if($receivedNum >= $receiverInfo['receive_num']){
            $receiveStatus = 3;
        }
        $upData = [
            'received_num' => $receivedNum,
            'receive_status' => $receiveStatus,
        ];
        if(!$receiverInfo['received_num']) {
            $upData['receive_date'] = Carbon::now()->toDateTimeString();
        }
        $res = (new ReceiversRepository)->updateFields($id, $upData);
        if (!$res) {
            return false;
        }

        return true;
    }

    /**
     * 获取字段聚合数量
     * @param $query
     * @param $field
     * @return array|mixed
     */
    public static function getFieldGroupNum($query = [], $field = '')
    {
        $query['group_field'] = $field;
        $query['select_raw'] = "{$field}, count(1) num";

        return self::getList($query);
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public static function del($id) {
        $res = (new ReceiversRepository())->updateFields($id, [
            'deleted_at' => Carbon::now()->toDateTimeString(),
        ]);
        if (!$res) {
            return resultError('删除失败');
        }

        return resultSuccess([], '删除成功');
    }

    /**
     * 修改领取资格
     * @param $id
     * @param $status
     * @param $remark
     * @return array
     */
    public static function updateReceiverStatus($id, $status, $remark = '') {
        $data = [
            'receiver_status' => $status,
            'receiver_status_remark' => $remark,
        ];
        $res = (new ReceiversRepository())->updateFields($id, $data);
        if (!$res) {
            return resultError('更新失败');
        }

        return resultSuccess([], '更新成功');
    }

}
